import { store } from '../index';
import { defineStore } from 'pinia';
import { useCache } from '@/hooks/useCache';
import { nextTick } from 'vue';
const { wsCache } = useCache();
// import { removeToken } from '@/utils/auth';
// import { getCompanyInfo } from "@/api/systemSetting/index";
// import { getUserInfo, getLogOut, getUserList } from "@/api/common/index";
// const message = useMessage();
interface UserInfoVO {
	userInfo: object,
	companyInfo: object,
	userList: string[],
	viewInfo: string[],
	menuIndex: number
}

export const useUserStore = defineStore('admin-user', {
	state: (): UserInfoVO => ({
		userInfo: {}, // 个人信息
		companyInfo: {}, // 公司信息
		userList: [],
		viewInfo: [], // 各个新视图信息
		menuIndex: wsCache.get('menuIndex') || 0
	}),
	getters: {
		// getUserInfo(state): object { return state.userInfo; },
		// getCompanyInfo(state): object { return state.companyInfo; },
		// getUserList(state): string[] { return state.userList; },
		getViewInfo(state): string[] { return state.viewInfo; },
	},
	actions: {
		setMenuIndex(data){
			this.menuIndex = data;
			wsCache.set('menuIndex', data);
		},
		// // 用户信息
		// async setUserInfo() {
		// 	try {
		// 		const res = await getUserInfo();
		// 		wsCache.set('userInfo', res);
		// 	} catch (err) {
		// 		console.log(err);
		// 	}
		// },
		// // 退出登录
		// async setLogOut() {
		// 	await message.delConfirm(`确认退出系统吗？`);
		// 	try {
		// 		await getLogOut();
		// 		removeToken();
		// 		wsCache.clear();
		// 		window.location.href = `http://192.168.10.19:5173/login`;
		// 	} catch (err) {
		// 		console.log(err);
		// 	}
		// },
		// // 公司信息
		// async setCompanyInfo() {
		// 	try {
		// 		const res = await getCompanyInfo();
		// 		wsCache.set('companyInfo', res);
		// 	} catch (err) {
		// 		console.log(err);
		// 	}
		// },
		// // 所有用户
		// async setUserList() {
		// 	try {
		// 		const res = await getUserList();
		// 		this.userList = res || [];
		// 		wsCache.set('userList', res);
		// 	} catch (err) {
		// 		console.log(err);
		// 	}
		// },
		// 新视图信息
		setViewInfo(data:any) {
			const isHave = this.viewInfo.some((item: any) => item.page === data.page);
			console.log('拿到====', isHave, { ...data });
			if (!isHave) {
				this.viewInfo.push(data);
			} else {
				this.viewInfo.map((item: any) => {
					if (item.page === data.page) {
						Object.keys(item).forEach(keys => {
							item[keys] = data[keys];
						});
					}
					return item;
				});
			}
			nextTick(() => {
				wsCache.set('viewInfo', this.viewInfo);
			});
		}
	}
});

export const useUserStoreWithOut = () => {
	return useUserStore(store);
};
